package com.bjdd.jdy.ui.working;


import android.content.Intent;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.support.design.widget.TabLayout;
import android.support.v4.app.Fragment;
import android.support.v4.content.ContextCompat;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.bjdd.jdy.App;
import com.bjdd.jdy.Constant;
import com.bjdd.jdy.R;
import com.bjdd.jdy.adapter.TakeOrderAdapter;
import com.bjdd.jdy.baidu.LocationUtils;
import com.bjdd.jdy.baidu.MyService;
import com.bjdd.jdy.baidu.NaviUtils;
import com.bjdd.jdy.base.BaseFragment;
import com.bjdd.jdy.base.RxManager;
import com.bjdd.jdy.entity.OrderBean;
import com.bjdd.jdy.entity.RoutePoint;
import com.bjdd.jdy.entity.User;
import com.bjdd.jdy.entity.result.TodayDataResult;
import com.bjdd.jdy.util.ImageUtil;
import com.bjdd.jdy.util.JumpUtil;
import com.bjdd.jdy.util.L;
import com.bjdd.jdy.util.SpUtil;
import com.bjdd.jdy.util.T;
import com.bjdd.jdy.view.other.CustomDialog;
import com.bjdd.jdy.view.other.DividerItemDecoration;
import java.util.ArrayList;
import java.util.List;

import butterknife.Bind;
import butterknife.OnClick;
import in.srain.cube.views.ptr.PtrClassicDefaultFooter;
import in.srain.cube.views.ptr.PtrClassicDefaultHeader;
import in.srain.cube.views.ptr.PtrDefaultHandler2;
import in.srain.cube.views.ptr.PtrFrameLayout;

/**
 * A simple {@link Fragment} subclass.
 */
public class WorkingFragment extends BaseFragment<WorkingPresenter, WorkingModel> implements WorkingContract.View {

    @Bind(R.id.img_working_head)
    ImageView imgHead;
    @Bind(R.id.tv_working_mobile)
    TextView tvMobile;
    @Bind(R.id.tv_working_state)
    TextView tvState;
    @Bind(R.id.tv_working_money)
    TextView tvMoney;
    @Bind(R.id.tv_working_time)
    TextView tvTime;
    @Bind(R.id.rcv_working)
    RecyclerView rcv;
    @Bind(R.id.swiperefreshlayout)
    PtrFrameLayout refreshlayout;
    @Bind(R.id.btn_work)
    Button btnWork;
    @Bind(R.id.tl_work_tab)
    TabLayout tabLayout;
    private User user;
    private ImageUtil imageUtil;
    private TakeOrderAdapter grabAdapter,pickAdapter,deliveryAdapter;
    private List<OrderBean> grabData,pickData,deliveryData;
    private CountDownTimer timer;
    private final long timeSpace = 1000;
    private final long countTime = 60*timeSpace*60*24;
    private int workTime;
    private int grabPage = 0,pickPage = 0,deliveryPage = 0;
    private final int size = 10;
    private RxManager rxManager = new RxManager();
    private boolean isLoadMore = false;
    private CustomDialog mDialog;
    @Override
    public int getLayoutId() {
        return R.layout.fragment_working;
    }

    @Override
    public void initView() {
        tabLayout.addTab(tabLayout.newTab().setText("抢 单"));
        tabLayout.addTab(tabLayout.newTab().setText("待取货"));
        tabLayout.addTab(tabLayout.newTab().setText("待送货"));
        initPtrFrameLayout();
        refreshlayout.autoRefresh();
        tabLayout.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
            @Override
            public void onTabSelected(TabLayout.Tab tab) {
                refreshlayout.autoRefresh();
                switch (tab.getPosition()){
                    case 0:
                        //抢单
                        //swiperefreshlayout.setRefreshing(true);
                        grabPage = 0;
                        presenter.queryWaitOrder(grabPage,size);
                        rcv.setAdapter(grabAdapter);
                        break;
                    case 1:
                        //待取货
                        //swiperefreshlayout.setRefreshing(true);
                        refreshlayout.autoRefresh();
                        pickPage = 0;
                        presenter.queryOrder(Constant.ORDER_PAIR,pickPage,size);
                        rcv.setAdapter(pickAdapter);
                        break;
                    case 2:
                        //待送货
                        //swiperefreshlayout.setRefreshing(true);
                        refreshlayout.autoRefresh();
                        deliveryPage = 0;
                        presenter.queryOrder(Constant.ORDER_SENDING,deliveryPage,size);
                        rcv.setAdapter(deliveryAdapter);
                        break;
                }
            }

            @Override
            public void onTabUnselected(TabLayout.Tab tab) {

            }

            @Override
            public void onTabReselected(TabLayout.Tab tab) {

            }
        });
        rcv.setLayoutManager(new LinearLayoutManager(context));
        rcv.addItemDecoration(new DividerItemDecoration(context,
                DividerItemDecoration.VERTICAL_LIST));
        imageUtil = new ImageUtil(context);
        user = SpUtil.getUser();
        setInfo();
        initAdapter();
        rxManager.on(Constant.NAV,msg -> startNav((RoutePoint)msg));
        timer = new CountDownTimer(countTime,timeSpace) {
            @Override
            public void onTick(long millisUntilFinished) {
                addWorkTime();
            }

            @Override
            public void onFinish() {

            }
        };
        rxManager.on(Constant.INSPECTION_FINISH,msg -> inspectionFinish());
        rxManager.on(Constant.SIGN_ORDER_BACK,msg -> signFinish());
        rxManager.on(Constant.SIGN_SCAN_SUCCESS,msg -> signScanSuccess());
    }

    private void initPtrFrameLayout(){

        PtrClassicDefaultHeader header = new PtrClassicDefaultHeader(context);
        header.onUIRefreshBegin(refreshlayout);
        refreshlayout.setHeaderView(header);
        refreshlayout.addPtrUIHandler(header);
        PtrClassicDefaultFooter footer = new PtrClassicDefaultFooter(context);
        footer.onUIRefreshBegin(refreshlayout);
        refreshlayout.setFooterView(footer);
        refreshlayout.addPtrUIHandler(footer);
        refreshlayout.setLoadingMinTime(1000);
        refreshlayout.setPtrHandler(new PtrDefaultHandler2() {
            @Override
            public void onLoadMoreBegin(PtrFrameLayout frame) {
                isLoadMore = true;
                switch (tabLayout.getSelectedTabPosition()){
                    case 0:
                        //抢单
                        grabPage ++;
                        presenter.queryWaitOrder(grabPage,size);
                        break;
                    case 1:
                        //待取货
                        pickPage ++;
                        presenter.queryOrder(Constant.ORDER_PAIR,pickPage,size);
                        break;
                    case 2:
                        //待送货
                        deliveryPage ++;
                        presenter.queryOrder(Constant.ORDER_SENDING,deliveryPage,size);
                        break;
                }
            }

            @Override
            public void onRefreshBegin(PtrFrameLayout frame) {
                isLoadMore = false;
                switch (tabLayout.getSelectedTabPosition()){
                    case 0:
                        //抢单
                        grabPage = 0;
                        presenter.queryWaitOrder(grabPage,size);
                        break;
                    case 1:
                        //待取货
                        pickPage = 0;
                        presenter.queryOrder(Constant.ORDER_PAIR,pickPage,size);
                        break;
                    case 2:
                        //待送货
                        deliveryPage = 0;
                        presenter.queryOrder(Constant.ORDER_SENDING,deliveryPage,size);
                        break;
                }
            }
        });
    }

    /**
     * 显示界面信息
     */
    private void setInfo(){
        if (user == null){
            return;
        }
        tvMobile.setText(user.getRealName());
        if (user.isWorkStatus()){
            tvState.setText("出工中");
            btnWork.setText("收工");
            LocationUtils.getInstance(context).start();
        }else {
            tvState.setText("未出工");
            btnWork.setText("出工");
        }
        if(!TextUtils.isEmpty(user.getPhoto())){
            imageUtil.loadCircleImage(user.getPhoto(),imgHead);
        }
    }

    /**
     * 初始化adapter
     */
    private void initAdapter(){
        L.d("初始化适配器");
        grabData = new ArrayList<>();
        pickData = new ArrayList<>();
        deliveryData = new ArrayList<>();
        grabAdapter = new TakeOrderAdapter(context,grabData);
        pickAdapter = new TakeOrderAdapter(context,pickData);
        deliveryAdapter = new TakeOrderAdapter(context,deliveryData);
        rcv.setAdapter(grabAdapter);
        refreshlayout.autoRefresh();
        presenter.queryWaitOrder(grabPage,size);
    }

    private long exitTime = 0;
    @OnClick({R.id.btn_work})
    public void click(View view){
        switch (view.getId()){
            case R.id.btn_work:
                if (user.isWorkStatus()){
                    //当前是出工状态，则收工
                    if((System.currentTimeMillis()-exitTime) < 10000){
                        T.show("请在10秒后收工");
                    } else {
                        presenter.finshWork();
                        exitTime = System.currentTimeMillis();
                    }
                }else {
                    //当前为收工状态，则出工
                    if((System.currentTimeMillis()-exitTime) < 10000){
                        T.show("请在10秒后开工");
                    } else {
                        presenter.startWork();
                        exitTime = System.currentTimeMillis();
                    }
                }
                break;
        }
    }

    @Override
    public void todatData(TodayDataResult result) {
        L.d("获取时间返回");
        if (result!=null){
            L.d("时间结果不为空");
            /*double f1 = result.getIncome().setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue();
            L.d("金额："+f1);*/
            tvMoney.setText("￥"+result.getIncome());
            //tvTime.setText(result.getWorkTime());
            workTime = result.getWorkTime();
            workTime --;
            addWorkTime();
            if(user.isWorkStatus()){
                timer.start();
            }
        }
    }

    @Override
    public void startWorkBack() {
        user = SpUtil.getUser();
        setInfo();
        timer.start();
        Intent intent = new Intent(context,MyService.class);
        intent.putExtra("imei",user.getCarrierId());
        context.startService(intent);
        LocationUtils.getInstance(context).start();
    }

    @Override
    public void stopWorkBack() {
        user = SpUtil.getUser();
        setInfo();
        L.d("停止timer");
        timer.cancel();
        MyService.stopTrace();
        LocationUtils.getInstance(context).stop();
    }

    @Override
    public void orderBack(int type, List<OrderBean> list) {
        switch (type){
            case Constant.ORDER_PAID:
                //可抢订单
                if (isLoadMore){
                    grabData.addAll(list);
                }else {
                    grabData.clear();
                    grabData.addAll(list);
                }
                grabAdapter.notifyDataSetChanged();
                break;
            case Constant.ORDER_PAIR:
                //待取货
                if (isLoadMore){
                    pickData.addAll(list);
                }else {
                    pickData.clear();
                    pickData.addAll(list);
                }
                pickAdapter.notifyDataSetChanged();
                break;
            case Constant.ORDER_SENDING:
                //待送货
                if (isLoadMore){
                    deliveryData.addAll(list);
                }else {
                    deliveryData.clear();
                    deliveryData.addAll(list);
                }
                deliveryAdapter.notifyDataSetChanged();
                break;
        }
        refreshlayout.refreshComplete();
    }

    @Override
    public void grabBack() {
        tabLayout.getTabAt(1).select();
        //swiperefreshlayout.setRefreshing(true);
        refreshlayout.autoRefresh();
        rcv.setAdapter(pickAdapter);
        pickPage = 0;
        presenter.queryOrder(Constant.ORDER_PAIR,pickPage,size);
    }

    @Override
    public void showGrapDialog(long orderId) {
        if (mDialog == null){
            CustomDialog.Builder builder;
            builder = new CustomDialog.Builder(context);
            mDialog = builder.setMessage("确认抢单")
                    .setPositiveButton("确定", new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            mDialog.dismiss();
                            presenter.grab(orderId);
                        }
                    })
                    .setNegativeButton("取消", new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            mDialog.dismiss();
                        }
                    })
                    .createTwoButtonDialog();
        }
        mDialog.show();
    }

    @Override
    public void loadingError() {
        refreshlayout.refreshComplete();
    }

    private void addWorkTime(){
        workTime ++;
        String str = "";
        int hour = workTime / (60*60);
        int minute = ( ( workTime - ( hour * 60 * 60)) / 60);
        int seconed = workTime - ( minute * 60 ) - ( hour * 60 * 60);
        String hourStr = String.format("%02d", hour);
        String minuteStr = String.format("%02d", minute);
        String sencondStr = String.format("%02d", seconed);
        str = hourStr + ":" + minuteStr + ":" + sencondStr;
        if (tvTime!=null){
            tvTime.setText(str);
        }
    }

    private void startNav(RoutePoint point){
        NaviUtils.getInstance(getActivity()).start(point);
    }

    @Override
    public void onDestroy() {
        if (timer !=null ){
            timer.cancel();
            timer = null;
        }
        super.onDestroy();
    }

    @Override
    public void onPause() {
        super.onPause();
        presenter.onPause();
    }

    private void inspectionFinish(){
        //swiperefreshlayout.setRefreshing(true);
        refreshlayout.autoRefresh();
        pickPage = 0;
        presenter.queryOrder(Constant.ORDER_PAIR,pickPage,size);
    }
    private void signFinish(){
        //swiperefreshlayout.setRefreshing(true);
        refreshlayout.autoRefresh();
        deliveryPage = 0;
        presenter.queryOrder(Constant.ORDER_SENDING,deliveryPage,size);
        presenter.getTodayData();
    }
    private void signScanSuccess(){
        tabLayout.getTabAt(2).select();
    }



}
